package com.myproject.utils;

import org.apache.hc.client5.http.classic.methods.*;
import org.apache.hc.client5.http.config.*;
import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy;
import org.apache.hc.client5.http.impl.classic.*;
import org.apache.hc.client5.http.impl.io.*;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.io.entity.*;
import org.apache.hc.core5.util.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;

/**
 * 修复版HttpClient工具类（适配HttpClient 5.3.1）
 */
public class HttpClientUtils {

    private static final Timeout CONNECT_TIMEOUT = Timeout.ofSeconds(3);
    private static final Timeout RESPONSE_TIMEOUT = Timeout.ofSeconds(10);
    private static final int MAX_TOTAL_CONNECTIONS = 200;
    private static final int MAX_PER_ROUTE = 50;
    private static final TimeValue IDLE_CONN_TIMEOUT = TimeValue.ofSeconds(30);

    private static volatile CloseableHttpClient httpClient;
    private static final IdleConnectionMonitorThread monitorThread;

    static {
        // 1. 连接池配置（使用PoolingHttpClientConnectionManager）
        PoolingHttpClientConnectionManager connManager = 
            PoolingHttpClientConnectionManagerBuilder.create()
            .setMaxConnTotal(MAX_TOTAL_CONNECTIONS)
            .setMaxConnPerRoute(MAX_PER_ROUTE)
            .build();

        // 2. 请求配置
        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECT_TIMEOUT)
            .setResponseTimeout(RESPONSE_TIMEOUT)
            .setConnectionRequestTimeout(Timeout.ofSeconds(1))
            .build();

        // 3. 创建HttpClient实例
        httpClient = HttpClients.custom()
            .setConnectionManager(connManager)
            .setDefaultRequestConfig(requestConfig)
            .setRetryStrategy(new DefaultHttpRequestRetryStrategy(2, TimeValue.ofSeconds(1)))
            .evictIdleConnections(IDLE_CONN_TIMEOUT)
            .build();

        // 4. 启动监控线程（传入具体实现类）
        monitorThread = new IdleConnectionMonitorThread(connManager);
        monitorThread.setDaemon(true);
        monitorThread.start();
    }

    // ------------------- 公有方法 -------------------
    // ...（原有doGet/doPostJson等方法保持不变）...

    // ------------------- 修复的连接监控线程 -------------------
    private static class IdleConnectionMonitorThread extends Thread {
        private final PoolingHttpClientConnectionManager connMgr; // 使用具体实现类
        private volatile boolean shutdown;

        public IdleConnectionMonitorThread(PoolingHttpClientConnectionManager connMgr) {
            super("HttpClient-Connection-Monitor");
            this.connMgr = connMgr;
        }

        @Override
        public void run() {
            try {
                while (!shutdown) {
                    synchronized (this) {
                        wait(5000);
                        // 修复点1：使用5.x新API [1,6](@ref)
                        connMgr.closeExpired(); // 替换closeExpiredConnections()
                        connMgr.closeIdle(IDLE_CONN_TIMEOUT); // 替换closeIdleConnections()
                    }
                }
            } catch (InterruptedException ignored) {
                shutdown();
            }
        }

        // 修复点2：明确定义shutdown方法 [2,4](@ref)
        public void shutdown() {
            shutdown = true;
            interrupt(); // 中断等待状态
        }
    }

    /**
     * 关闭HttpClient及监控线程
     */
    public static void close() throws IOException {
        monitorThread.shutdown(); // 调用自定义shutdown方法
        if (httpClient != null) {
            httpClient.close();
        }
    }
}